package cn.wit.summit.chwan.ui.base;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDex;
import android.util.SparseArray;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.mob.MobSDK;
import com.umeng.commonsdk.UMConfigure;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.models.dbmanager.upgrade.MyDevOpenHelper;
import cn.wit.summit.chwan.models.dto.CfgBean;
import cn.wit.summit.chwan.models.dto.CfgExplainBean;
import cn.wit.summit.chwan.models.dto.DiscoveryType;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.greendao.gen.DaoMaster;
import cn.wit.summit.chwan.models.greendao.gen.DaoSession;
import cn.wit.summit.chwan.models.greendao.gen.DotRequestTableDao;
import cn.wit.summit.chwan.models.greendao.gen.DownLoadTaskTableDao;
import cn.wit.summit.chwan.models.greendao.gen.HistorySearchTableDao;
import cn.wit.summit.chwan.models.greendao.gen.NetResultCacheTableDao;
import cn.wit.summit.chwan.models.response.GameLibraryV3Response;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.tools.downloadtool.DownloadFactory;
import cn.wit.summit.chwan.tools.downloadtool.DownloadTool;
import cn.wit.summit.chwan.ui.service.ChWService;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.AppInfoUtil;
import cn.wit.summit.chwan.utils.JsonMapper;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StethoUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import okhttp3.OkHttpClient;

/**
 * Created by tangbingliang on 17/2/16.
 */

public class MyApplication extends Application {

    private String dbName = "";
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private DaoMaster.DevOpenHelper mHelper;
    private NetResultCacheTableDao mNetResultCacheTableDao;
    private DownLoadTaskTableDao mDownLoadTaskTableDao;
    private HistorySearchTableDao mHistorySearchTableDao;
    private DotRequestTableDao mDotRequestTableDao;
    private SharedPreferences sp, ps;
    private String appRootPath;
    private SparseArray<DiscoveryType> discoveryTypes;
    public static int bannerPo = 0;
    public static long bannerTime = 0;
    public static AccountBean accountBean;
    public static CfgBean cfgPlug;
    public static CfgExplainBean arrayCommentExplain;
    public static CfgExplainBean arrayUploadExplain;
    public static int commentAddEnergy = 0;
    public static Map<String, String> todayWard = new HashMap<>();
    public static float downLoadRard = 0.0f;
    public static int downLoadWeekNum = 0;
    public static int downLoadDayNum = 0;

    private static MyApplication mMyInstance = null;

    public static MyApplication getMyApplication() {
        return mMyInstance;
    }

    public static AccountBean getAccountBean() {
        return accountBean;
    }
public  static Handler toastHandler=new Handler(){
    @Override
    public void handleMessage(Message msg) {

        ToastUtils.getInstance(getMyApplication()).showToastSystem("解压失败，请重试");
    }
};
    @Override
    public void onCreate() {
        super.onCreate();
        PreferenceUtil.saveBoolPreference(this, PreferenceUtil.PRE_PERMSSION_ALL, true);
        mMyInstance = this;
        initUMeng();
        AccountUtil.getInstance().getAccountData();
        setDatabase();
        initFresco();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                Intent intent = new Intent();
//                intent.setClass(getApplicationContext(), ChWService.class);
////                startService(intent);
//                MyJobIntentService.enqueueWork(getApplicationContext(), intent);
                try {
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(), ChWService.class);
                    startService(intent);
//                    MyJobIntentService.enqueueWork(getApplicationContext(), intent);
                } catch (Exception e) {
                    LogUtils.e("tbl>>>>111:"+e.getMessage());
                }

                initDownloadListener();

                MobSDK.init(mMyInstance);
                StethoUtils.initStetho(mMyInstance);
                initDiscoveryTypes();
            }
        }, 1500);

        List<DownLoadTaskTable> stayUnZipTasks = DownloadTaskManager.getInstance().findAllUNZIPDownloadTask();
        if (stayUnZipTasks!=null && stayUnZipTasks.size()>0) {
            for (DownLoadTaskTable downloadTask : stayUnZipTasks) {
                boolean hasinstal = APKUtils.getInstance(this).checkInstall(this, downloadTask.getPackageName());
                if (!hasinstal) {
                    downloadTask.setDownStatus(DownLoadStatusConfig.UNZIP_WAIT);
                    if (!StringUtils.isEmpty(downloadTask.getPackageName()))
                        DownloadTaskManager.getInstance().updateStatusByPackageName(downloadTask.getPackageName(), DownLoadStatusConfig.UNZIP_WAIT);
                    EventBus.getDefault().post(downloadTask.getDownEvent());
                }
            }
        }
    }

    public SparseArray<DiscoveryType> getDiscoveryTypes() {
        return discoveryTypes;
    }

    private void initDiscoveryTypes() {
        if (discoveryTypes == null) {
            discoveryTypes = new SparseArray<>();
        }

//     * '3' => '破解专题',
//     * '4' => '网游专题',
//     * '5' => '中文汉化专题',
//     * '6' => '大型游戏专题',
//     * '7' => '苹果专区专题',
//     * '8' => '谷歌专区专题',
//     * '9' => '总专题',
//     * '10' => '游戏分类',
        int i = 0;
        discoveryTypes.append(i++, new DiscoveryType(1, R.drawable.pojie, "破解"));
        discoveryTypes.append(i++, new DiscoveryType(2, R.drawable.wangyou, "网游"));
        discoveryTypes.append(i++, new DiscoveryType(3, R.drawable.zhongwenhuanhua, "汉化"));
//        discoveryTypes.append(i++, new DiscoveryType(4, R.drawable.daxingyouxi, "大型游戏"));
//        discoveryTypes.append(i++, new DiscoveryType(5, R.drawable.iphone, "苹果专区"));
//        discoveryTypes.append(i++, new DiscoveryType(6, R.drawable.googlezhuanqu, "谷歌专区"));
//        discoveryTypes.append(i++, new DiscoveryType(10, R.drawable.nvxing, "女性"));
        discoveryTypes.append(i++, new DiscoveryType(11, R.drawable.xiuxian, "休闲"));
//        discoveryTypes.append(i++, new DiscoveryType(9, R.drawable.qipai, "棋牌游戏"));
//        discoveryTypes.append(i++, new DiscoveryType(12, R.drawable.erciyuan, "二次元"));
        discoveryTypes.append(i++, new DiscoveryType(999, R.drawable.bangdan, "榜单"));
    }

    private void initFresco() {
        OkHttpClient okHttpClient = new OkHttpClient();
        ImagePipelineConfig config = OkHttpImagePipelineConfigFactory
                .newBuilder(this, okHttpClient)
                .build();
        Fresco.initialize(mMyInstance, config);
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this) ;
    }

    public static boolean isServiceRunning(Context context, String ServiceName) {
        try {

            if (("").equals(ServiceName) || ServiceName == null)
                return false;
            ActivityManager myManager = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                    .getRunningServices(100);
            for (int i = 0; i < runningService.size(); i++) {
                LogUtils.e("service name " + runningService.get(i).service.getClassName().toString());
                if (runningService.get(i).service.getClassName().toString()
                        .equals(ServiceName)) {
                    return true;
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean serviceHasRouning = false;

    private void initDownloadListener() {
        DownloadFactory.get().setDownloadListener(new DownloadFactory.DownloadListener() {
            @Override
            public void onChangeStatus(DownloadEvent downloadEvent) {
                LogUtils.e("downloadEvent.status:"+downloadEvent.status);

                if (serviceHasRouning || isServiceRunning(getApplicationContext(), "cn.wit.summit.chwan.ui.service.ChWService")) {
                    LogUtils.e("serviceHasRunning");
                } else {
                    try {
                        Intent intent = new Intent();
                        intent.setClass(getApplicationContext(), ChWService.class);
                        startService(intent);
//                        MyJobIntentService.enqueueWork(getApplicationContext(), intent);
                    } catch (Exception e) {
                        LogUtils.e("tbl>>>>222:"+e.getMessage());
                    }
                }

                if (downloadEvent.status== DownLoadStatusConfig.DOWNLOAD_ERROR){
                    StatFactory.getInstance().sendGameDownload(getApplicationContext(),downloadEvent.getGameId(),2+"",false);
                }else if (downloadEvent.status==DownLoadStatusConfig.DOWNLOAD_FINISH){
                    StatFactory.getInstance().sendGameDownload(getApplicationContext(),downloadEvent.getGameId(),1+"",false);
                }
                EventBus.getDefault().post(downloadEvent);

                if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOAD_FINISH) {
                    //do install
                    DownLoadTaskTable downLoadTaskTable = DownloadTaskManager.getInstance().findByGameId(downloadEvent.gameId);
                    switch (downLoadTaskTable.getGameType()) {
                        case 0:
                            StatFactory.getInstance().sendGameDownLoadDone(mMyInstance, downloadEvent.gameId);
                            downloadEvent.setStatus(DownLoadStatusConfig.INSTALL_WAIT);
                            EventBus.getDefault().post(downloadEvent);
                            DownloadTaskManager.getInstance().updateStatusBygameId(downloadEvent.gameId, DownLoadStatusConfig.INSTALL_WAIT);
                            APKUtils.getInstance(mMyInstance).installAPK(mMyInstance, downLoadTaskTable.getDownPath(), downloadEvent.gameId);
                            break;
                        case 1:
                        case 2:
                            StatFactory.getInstance().sendUnZip(mMyInstance,downloadEvent.getGameId(),3+"");
                            downloadEvent.setStatus(DownLoadStatusConfig.UNZIP_WAIT);
                            EventBus.getDefault().post(downloadEvent);
                            DownloadTaskManager.getInstance().updateStatusBygameId(downloadEvent.gameId, DownLoadStatusConfig.UNZIP_WAIT);
                            DownloadTool.unzip(mMyInstance, downLoadTaskTable);
                            break;
                    }

                }
            }
        });
    }

    public SharedPreferences getShareFer() {
        sp = getSharedPreferences("setLogin", MODE_PRIVATE);
        return sp;
    }

    public SharedPreferences getRedps() {
        ps = getSharedPreferences("Red", MODE_PRIVATE);
        return ps;
    }

    public DotRequestTableDao getmDotRequestTableDao() {
        return mDotRequestTableDao;
    }

    private void initUMeng() {
        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, "");
        //设置组件化的Log开关 参数: boolean 默认为false，如需查看LOG设置为true
        UMConfigure.setLogEnabled(true);
        //设置日志加密 参数：boolean 默认为false（不加密）
        UMConfigure.setEncryptEnabled(false);
    }

    /**
     * 设置greenDao
     */
    private void setDatabase() {
        dbName = AppInfoUtil.getAppPkName(this).substring(AppInfoUtil.getAppPkName(this).lastIndexOf(".") + 1);
        LogUtils.e("tbl>>>dbName:" + dbName);
        // 通过DaoMaster 的内部类 DevOpenHelper，你可以得到一个便利的SQLiteOpenHelper 对象。
        // 可能你已经注意到了，你并不需要去编写「CREATE TABLE」这样的 SQL 语句，因为greenDAO 已经帮你做了。
        // 注意：默认的DaoMaster.DevOpenHelper 会在数据库升级时，删除所有的表，意味着这将导致数据的丢失。
        // 所以，在正式的项目中，你还应该做一层封装，来实现数据库的安全升级。

//        mHelper = new DaoMaster.DevOpenHelper(this, dbName, null);
//        db = mHelper.getWritableDatabase();

        //用于数据库保留数据升级
        MyDevOpenHelper mMyDevOpenHelper = new MyDevOpenHelper(this, dbName, null);
        db = mMyDevOpenHelper.getWritableDatabase();
        // 注意：该数据库连接属于DaoMaster，所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
        mDotRequestTableDao = mDaoSession.getDotRequestTableDao();
        mNetResultCacheTableDao = mDaoSession.getNetResultCacheTableDao();
        mDownLoadTaskTableDao = mDaoSession.getDownLoadTaskTableDao();
        mHistorySearchTableDao = mDaoSession.getHistorySearchTableDao();
        try {
            String cfgString = PreferenceUtil.geteNergyUrlPreferences(getApplicationContext());
            if (StringUtils.isNotEmpty(cfgString)){
                cfgPlug = JsonMapper.getInstance().fromJson(cfgString, CfgBean.class);
            }
            if (cfgPlug==null||StringUtils.isEmpty(cfgPlug.getValue_energy_secret_url())) {
                cfgPlug = new CfgBean();
                cfgPlug.setValue_energy_secret_url("https://app-web.abab618.com/task.html");
                cfgPlug.setValue_feedback_url("https://app-web.abab618.com/feedback.html");
                cfgPlug.setValue_share_invite_game_url("https://app-web.abab618.com/share_invite_game.html?game_id=");
                cfgPlug.setValue_share_invite_url("https://app-web.abab618.com/share_invite.html");
                cfgPlug.setValue_wallet_url("http://testchw.usercenter.papa91.com/static/wallet.html");
                cfgPlug.setValue_game_upload_url("https://app-web.abab618.com/feedback.html");
            }
        } catch (Exception e) {
            e.printStackTrace();
            cfgPlug = new CfgBean();
            cfgPlug.setValue_energy_secret_url("https://app-web.abab618.com/task.html");
            cfgPlug.setValue_feedback_url("https://app-web.abab618.com/feedback.html");
            cfgPlug.setValue_share_invite_game_url("https://app-web.abab618.com/share_invite_game.html?game_id=");
            cfgPlug.setValue_share_invite_url("https://app-web.abab618.com/share_invite.html");
            cfgPlug.setValue_wallet_url("http://testchw.usercenter.papa91.com/static/wallet.html");
            cfgPlug.setValue_game_upload_url("https://app-web.abab618.com/feedback.html");
        }
    }

    public HistorySearchTableDao getmHistorySearchTableDao() {
        return mHistorySearchTableDao;
    }

    public DownLoadTaskTableDao getmDownLoadTaskTableDao() {
        return mDownLoadTaskTableDao;
    }

    public SQLiteDatabase getmDownLoadTaskTableDb() {
        return db;
    }

    public NetResultCacheTableDao getmNetResultCacheTableDao() {
        return mNetResultCacheTableDao;
    }

    /**
     * 但是当我们没在AndroidManifest.xml中设置其debug属性时:
     * 使用Eclipse运行这种方式打包时其debug属性为true,使用Eclipse导出这种方式打包时其debug属性为法false.
     * 在使用ant打包时，其值就取决于ant的打包参数是release还是debug.
     * 因此在AndroidMainifest.xml中最好不设置android:debuggable属性置，而是由打包方式来决定其值.
     */
    public boolean isApkDebugable() {
        try {
            ApplicationInfo info = getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            LogUtils.e(">>>BaseApplication>>>e:" + e.toString());
        }
        return false;
    }

    public void setAppRootPath(String appRootPath) {
        this.appRootPath = appRootPath;
    }

    public String getDbName() {
        if (StringUtils.isEmpty(dbName))
            dbName = "wufun";
        return dbName;
    }

    public String getAppRootPath() {
        return appRootPath;
    }
}
